//==========================================================================================
// BEGIN: jQuery Extend
jQuery.extend({
  isUndefined: function(obj){
    return typeof(obj) == "undefined" ? true : false;
  },
  exists: function(obj){
    return jQuery(obj).length != 0 ? true : false ;
  },
  browserDetection: function(appendTo) {
    var bindToElm = (jQuery.isUndefined(appendTo) ? jQuery("body") : jQuery(appendTo));
	var userAgent= "";
    jQuery.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); 
    if(jQuery.browser.msie) { // Is this a version of IE?
      bindToElm.addClass("browser_ie");        
      bindToElm.addClass("browser_ie" + jQuery.browser.version.substring(0,1));
    }
    if(jQuery.browser.chrome) { // Is this a version of Chrome?
      bindToElm.addClass("browser_chrome");
      userAgent = userAgent.substring(userAgent.indexOf("chrome/") +7);
      userAgent = userAgent.substring(0,1);
      bindToElm.addClass("browser_chrome" + userAgent);  
      jQuery.browser.safari = false; // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
    }
    if(jQuery.browser.safari) { // Is this a version of Safari?
      bindToElm.addClass("browser_safari");        
      userAgent = userAgent.substring(userAgent.indexOf("version/") +8);
      userAgent = userAgent.substring(0,1);
      bindToElm.addClass("browser_safari" + userAgent);
    }
    if(jQuery.browser.mozilla) { // Is this a version of Mozilla?
      if(navigator.userAgent.toLowerCase().indexOf("firefox") != -1) { //Is it Firefox?
        bindToElm.addClass('browser_firefox');
        userAgent = userAgent.substring(userAgent.indexOf("firefox/") +8);
        userAgent = userAgent.substring(0,1);
        bindToElm.addClass("browser_firefox" + userAgent);
      } else { // If not then it must be another Mozilla
        bindToElm.addClass("browser_mozilla");
      }
    }
  },
  getRootDomain: function(){
    var rootDomain = document.location.hostname;
    if(rootDomain.match(/localhost/gi)){
      return finalDomain = "localhost";
    }
    else{
      var split = rootDomain.split('.');
      return "." + split[split.length-2] + "." + split[split.length-1];
    }  
  },
  getHashValue: function(){
    return window.location.hash;
  }  
});
jQuery.fn.extend({
    trunc: function(count, append) {
        //Used for string truncation
          return (isNaN(count)) ? this : this.each(function() {
                var _this = jQuery(this);
                var curCount = 0;
                var boolCount = true;
                var curChar = "";
                var curString = _this.html();
                var tempString = "";
                var truncAppend = append;
                for(var i=0; i<curString.length; i++) {
        curChar = curString.charAt([i]);
        tempString += curChar;
        switch(curChar) {
            case "<":
              boolCount = false;
              break;
            case ">":
              boolCount = true;
              break;
            default:
              if(boolCount) {
                  curCount++;
              }
        }
        if(curCount == count) {
            _this.html(tempString + (jQuery.isUndefined(truncAppend) ? "..." : truncAppend));
            break;
        }
                }
          });
    },
    outerHTML: function(obj){
      return jQuery("<div>").append(jQuery(this).clone()).html();
    },
    popupWindow: function(name, width, height, spec){
      jQuery(this).live('click', function(e){
        e.preventDefault();
        var winName = name.replace(/[ -\/&#]/gi,'');
        var theWidth = (width) ? width : 700;
        var theHeight = (height) ? height : 500;
        var winSpecs = 'width=' + width + ',height=' + height + ',' + (jQuery.isUndefined(spec) ? 'location=0,menuBar=1,resizable=1,scrollbars=1,status=1,toolbar=0,directories=0' : spec);
        window.open(this.href, winName, winSpecs);
    });    
  },
  defaultText: function(activeClass, defautlAttr) {
      //Toggle class based on default value
      var _this = jQuery(this);
      _this.val() != _this.attr(defautlAttr) ? _this.removeClass(activeClass) : (_this.hasClass(activeClass) ? "" : _this.addClass(activeClass));
      _this.focus(function(){
        if(_this.val() == _this.attr(defautlAttr)){
          _this.val('');
          _this.removeClass(activeClass);
        }
      }).blur(function(){
        if(_this.val() == ""){
          _this.val(_this.attr(defautlAttr));
          _this.addClass(activeClass);        
        }
      });

  }
});
// END: jQuery Extend

//==========================================================================================
// BEGIN: JavaScript and jQuery Plugins
// END: JavaScript and jQuery Plugins


//==========================================================================================
// BEGIN: jQuery functions on load

jQuery.noConflict();

jQuery(document).ready(function($) {
	// --------------------------------------------------------------------------------------
	// Apply browser detection classes to the body: browser_ie, browser_chrome, browser_firefox, browser_safari 
	$.browserDetection('body');

	// --------------------------------------------------------------------------------------
	// If JavaScript is enabled this adds "j_on" to body tag.
	$("body").addClass("j_on");
	
	// --------------------------------------------------------------------------------------
	// Homepage Slider
	if($.exists("#HomepageSlider")) {
		var prevThumb = '';
		var nextThumb = '';
		var ifIsNext = false;
		var prevNextIndex = 0;
		
		$("#HomepageSlider").cycle({
			fx: 'scrollHorz',
			speed: 1200,
			timeout: 12000,
			next: '#SliderNext',
			prev: '#SliderPrev',
			pause: 1,
			pauseOnPagerHover: 1,
			onPrevNextEvent: function(isNext, zeroBasedSlideIndex, slideElement) {
				console.log('[=============onPrevNextEvent==========');
				if(isNext) { ifIsNext = true; } else { ifIsNext = false; }
				console.log("zeroBasedSlideIndex: "+zeroBasedSlideIndex);
				prevNextIndex = zeroBasedSlideIndex;
				console.log('=============onPrevNextEvent==========]');
			},
			before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
				//get the current slide img 
				console.log('before: '+$(currSlideElement).index());
				if($(currSlideElement).index() == 0) {
					prevThumb = $(currSlideElement).parent('ul:first').children('li:last-child').find('img');
					if(ifIsNext) {
						//console.log('is next on 0: '+prevNextIndex);
						if (prevNextIndex-1 < 0) {prevNextIndex = $(currSlideElement).parent('ul:first').children().length();} else {prevNextIndex = prevNextIndex-1;}
						prevThumb = $(currSlideElement).parent('ul:first').children('li:nth-child('+prevNextIndex+')').find('img');
					} else {
						console.log('is prev on 0: '+prevNextIndex);
						prevThumb = $(currSlideElement).parent('ul:first').children('li:last-child').find('img');
					}
					
					console.log('true '+$(currSlideElement).parent('ul:first').children('li:last-child').find('img').attr('src'));
				} else {
					prevThumb = $(currSlideElement).find('img');
					console.log('false '+$(currSlideElement).find('img').attr('src'));
				}
				
				//check if the next slide exists
				if($(nextSlideElement).next('li').length > 0) {
					nextThumb = $(nextSlideElement).next('li').find('img');
				} else {
					nextThumb = $(nextSlideElement).parent('ul:first').children('li:first-child').find('img');
				}
				
				if($('#SliderPrev').find('img').length > 0) {
					$('#SliderPrev img').attr('src',prevThumb.attr('src'));
				} else {
					$('#SliderPrev').append('<img src="'+prevThumb.attr('src')+'" width="175" height="100" />');
				}
				
				if($('#SliderNext').find('img').length > 0) {
					$('#SliderNext img').attr('src',nextThumb.attr('src'));
				} else {
					$('#SliderNext').append('<img src="'+nextThumb.attr('src')+'" width="175" height="100" />');
				}
			},
			after: function(currSlideElement, nextSlideElement, options, forwardFlag)  {
				
			}
		});
		$('.slider_wrap .slider_nav_wrap').hover(function() {
			$(this).clearQueue().animate({width:"225px"}, 500);
		}, function() {
			$(this).clearQueue().animate({width:"25px"}, 500);
		});
	}
	
	// --------------------------------------------------------------------------------------
	// Signature Listings Detail Slider
	if($.exists("#SignatureDetailSlider")) {
		$("#SignatureDetailSlider").cycle({
			fx: 'scrollHorz',
			speed: 900,
			timeout: 8000,
			pause: 1,
			activePagerClass: 'active',
			pauseOnPagerHover: 1,
			pager: '#SignatureDetailSliderNav'
		});
	}
	
	// --------------------------------------------------------------------------------------
	// Bookmark functionality for Signature Listings
	if($.exists("span.bookmark")) {
		// add a "rel" attrib if Opera 7+
		if(window.opera) {
			if ($(".bookmark a").attr("rel") != ""){
				$(".bookmark a").attr("rel","sidebar");
			} 
		}
		$(".bookmark a",".detail_head").click(function(event){
			event.preventDefault();
			var url = this.href;
			var title = this.title;
	 
			if ($.browser.mozilla ) { // Mozilla Firefox Bookmark
				window.sidebar.addPanel(title, url,"");
			} else if( $.browser.msie ) { // IE Favorite
				window.external.AddFavorite( url, title);
			} else if(window.opera) { // Opera 7+
				return false; // do nothing
			} else {
				 alert('Unfortunately, this browser does not support the requested action,'
				 + ' please bookmark this page manually.');
			}
	 
		});
	}
	
	// --------------------------------------------------------------------------------------
	// Bookmark functionality for Signature Listings
	if($.exists("span.printer_friendly")) {
		$(".printer_friendly a",".detail_head").click(function(e){
			e.preventDefault();
			window.print();
		});
	}
	
	
});
// END: jQuery functions on load